<?php

use think\Config;
use think\Exception;
use think\helper\Arr;
use think\Model;
use think\facade\Db;

class Helper extends Model
{
    public $name="task_extension";



    /**
     * Notes:二维数组按某一字段排序
     * User:machangzhuo
     * DateTime: 2022/2/23 17:03
     * @param $array
     * @param $keys
     * @param string $sort
     * @return array
     */
    public function arraySort($array, $keys, $sort = 'asc')
    {
        if (empty($array)) return $array;
        $newArr = $valArr = array();
        foreach ($array as $key => $value) {
            $valArr[$key] = $value[$keys];
        }
        ($sort == 'asc') ? asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach ($valArr as $key => $value) {
            $newArr[$key] = $array[$key];
        }
        return $newArr;
    }

    /**
     * Notes:二维数组按某一字段排序
     * User:machangzhuo
     * DateTime: 2023/2/6 10:22
     * @param $data
     * @param $key
     * @return bool
     */
   public function arrayMultiSort($data,$key,$sort='DESC'){
         if(empty($key)) return $data;
         $sort=$sort=='DESC'?SORT_DESC:SORT_ASC;
         array_multisort(array_column($data, $key),$sort,$data);
         return $data;
    }


    /**
     * Notes:提取富文本中的纯文字
     * User:machangzhuo
     * DateTime: 2022/7/4 16:09
     * @param $str \app\api\model\文本内容
     * @param $num  \app\api\model\截取长度
     * @return string
     */
    public  function html2text($str,$num)
    {
        $str     = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
        $alltext = "";
        $start   = 1;
        for ($i = 0; $i < strlen($str); $i++) {
            if ($start == 0 && $str[$i] == ">") {
                $start = 1;
            } else if ($start == 1) {
                if ($str[$i] == "<") {
                    $start = 0;
                    $alltext .= " ";
                } else if (ord($str[$i]) > 31) {
                    $alltext .= $str[$i];
                }
            }
        }
        $alltext = str_replace("　", " ", $alltext);
        $alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
        $contents = preg_replace("/[ ]+/s", " ", $alltext);
        return mb_strlen($contents,'utf-8') > $num ? mb_substr($contents, 0, $num, "utf-8").'...' : mb_substr($contents, 0, $num, "utf-8");
    }


    /**
     * @param $img_file
     * @return string\
     * 本地图片转base64
     */
    public function imgToBase64($img_file) {
        $img_base64 = '';
        if (file_exists($img_file)) {
            $app_img_file = $img_file; // 图片路径
            $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等
            //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
            $fp = fopen($app_img_file, "r"); // 图片是否可读权限
            if ($fp) {
                $filesize = filesize($app_img_file);
                $content = fread($fp, $filesize);
                $file_content = chunk_split(base64_encode($content)); // base64编码
                switch ($img_info[2]) {           //判读图片类型
                    case 1: $img_type = "gif";
                        break;
                    case 2: $img_type = "jpg";
                        break;
                    case 3: $img_type = "png";
                        break;
                }
                $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码
            }
            fclose($fp);
        }
        return $img_base64; //返回图片的base64
    }

    /**
     * @param $img
     * @return string
     * 网络图片转base64
     */
    public function n_img_base_64($img){
        $imageInfo = getimagesize($img);
        return 'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($img)));
    }


    /**
     * Notes:检测参数是否存在
     * User:machangzhuo
     * DateTime: 2022/6/16 10:33
     * @param $in
     * @param $k
     * @return bool
     */
    public function is_param($in,$k){
        if(isset($in[$k])){
            if(!empty($in[$k])){
                return true;
            }else{
                return  false;
            }
        }else{
            return false;
        }
    }

    /**
     * Notes:处理分类数据
     * User:machangzhuo
     * DateTime: 2022/3/29 14:53
     * @param $data
     * @return array|bool
     */
    public static function handle($data)
    {
        static $result;
        if (empty($data)) return $data;
        foreach ($data as $k => $v) {
            $result[]['id'] = $v['id'];
            if (isset($v['_child'])) {
                $result = array_merge($result, self::handle($v['_child']));
            }
        }
        return $result;

    }


    /**
     * Notes:根据某一字段去重
     * User:machangzhuo
     * DateTime: 2022/3/25 15:30
     * @param $arr
     * @param $key
     * @return mixed
     */
    public function second_array_unique_bykey($arr, $key)
    {
        if (empty($arr)) return '';
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            {
                unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            } else {
                $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
            }
        }
        //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
        return $arr;

    }

    /**
     * Notes:获取二维数组指定值变成一维数组
     * User:machangzhuo
     * DateTime: 2022/4/19 9:24
     * @param $data
     * @return array
     */
    public function array_ids($data, $field = 'id')
    {
        if (empty($data)) return $data;
        $arr = [];
        foreach ($data as $k => $v) {
            if(!isset($v[$field])) return '';
            $arr[$k] = $v[$field];
        }
        return $arr;

    }


    /**
     * Notes:二维数组降维
     * User: machangzhuo
     * DateTime: 2022/1/4 10:52
     * @param $array
     * @return array
     */
    public function flareout_array($array)
    {
        if (empty($array)) return $array;

        $return = [];

        array_walk_recursive($array, function ($x) use (&$return) {

            $return[] = $x;
        });
        return $return;
    }


    /**
     * Notes:检查手机格式，中国手机不带国家代码，国际手机号格式为：国家代码-手机号
     * User:machangzhuo
     * DateTime: 2022/12/5 10:41
     * @param $mobile
     * @return bool
     */
    public  function is_mobile($mobile)
    {
        if (preg_match('/(^(13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{8})$/', $mobile)) {
            return true;
        } else {
            if (preg_match('/^\d{1,4}-\d{5,11}$/', $mobile)) {
                if (preg_match('/^\d{1,4}-0+/', $mobile)) {
                    //不能以0开头
                    return false;
                }

                return true;
            }

            return false;
        }
    }

    /**
     * Notes:隐藏手机号中间4位
     * User:machangzhuo
     * DateTime: 2022/6/10 14:56
     * @param $phone
     * @return string|string[]|null
     */
    public function hidetel($phone)
    {
        $IsWhat = preg_match('/(0[0-9]{2,3}[-]?[2-9][0-9]{6,7}[-]?[0-9]?)/i', $phone);
        if ($IsWhat == 1) {
            return preg_replace('/(0[0-9]{2,3}[-]?[2-9])[0-9]{3,4}([0-9]{3}[-]?[0-9]?)/i', '$1****$2', $phone);
        } else {
            return  preg_replace('/(1[356789]{1}[0-9])[0-9]{4}([0-9]{4})/i','$1****$2',$phone);
        }
    }



    /**
     * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
     * @param string $user_name 姓名
     * @return string 格式化后的姓名
     */
    public function substr_cut($user_name)
    {
        $strlen = mb_strlen($user_name, 'utf-8');
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        if ($strlen == 1) return $user_name;
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }


    /**
     * Notes:隐藏身份证号
     * User:machangzhuo
     * DateTime: 2022/5/25 17:12
     * @param $cert_no
     * @return string|string[]
     */
    public function cert_no($cert_no)
    {
        return strlen($cert_no['cert_no']) == 15 ? substr_replace($cert_no['cert_no'], "*******", 4, 7) : (strlen($cert_no['cert_no']) == 18 ? substr_replace($cert_no['cert_no'], "**********", 4, 10) : "");
    }


    /**
     * Notes:三维数组转二维数组
     * User: machangzhuo
     * DateTime: 2021/12/29 10:03
     * @param $array \app\api\model\传入参数
     * @return array
     */
    public function array3_to_array2($array)
    {
        $array = array_filter($array);
        $array = array_values($array);
        foreach ($array as $orderKey => $orderVal) {
            $count = count($orderVal);
            if ($count > 1) {
                for ($i = 0; $i < $count; $i++) {
                    $tempArr[] = $orderVal[$i];
                }
            } else {
                $tempArr[] = $orderVal[0];
            }
        }
        return $tempArr;
    }

    /**
     * 在数组指定位置插入数组
     * @param array $array 原数组
     * @param int $position 需要插入到原数组的位置
     * @param array $insert_array 需要插入的数组
     * @return array
     */
    public function designatPosInsertArr(&$array, $position, $insert_array)
    {
        $first_array = array_splice($array, 0, $position);
        $array = array_merge($first_array, $insert_array, $array);
        return $array;
    }

    /**
     * Notes:数组根据相同的值分组
     * User:machangzhuo
     * DateTime: 2022/6/10 9:44
     */
    public function array_grouping($data,$key='id')
    {
        $temp = [];
        foreach ($data as $k => $v) {
            $temp[$v[$key]][] = $v;
        }
        return $temp;
    }

    /**
     * Notes:多维数组转一维数组
     * User:machangzhuo
     * DateTime: 2022/6/10 14:53
     * @param $multi
     * @return array
     */
    public function arrToOne($multi)
    {
        $arr = array();
        foreach ($multi as $key => $val) {
            if (is_array($val)) {
                $arr = array_merge($arr, $this->arrToOne($val));
            } else {
                $arr[] = $val;
            }
        }
        return $arr;
    }

    /**
     * Notes:对象obj 转数组array
     * User:machangzhuo
     * DateTime: 2022/6/10 14:55
     * @param $object
     * @return mixed
     */
    public function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }


    /**
     * Notes:格式话数组包含time 字符的时间格式
     * User:machangzhuo
     * DateTime: 2022/12/20 10:14
     * @param $time
     * @param array $temp 不包含的字符
     * @param string $format
     * @return mixed
     */
    public function setTime($time,$temp=[],$format='Y-m-d'){
        if(empty($time)) return $time;
        $data=array_keys($time);
        $count=count($data);
        for($i=0;$i<$count;$i++){
            if(strstr($data[$i],'time') && !in_array($data[$i],$temp)){
                $time[$data[$i]]=date($format,strtotime($time[$data[$i]]));
            }
        }
        return $time;

    }

    /**
     * Notes:时间友好型提示风格化（即微博中的XXX小时前、昨天等等）
     * User:machangzhuo
     * DateTime: 2022/4/14 10:36
     * @param $timestamp
     * @param int $timeLimit
     * @param string $out_format
     * @param null $formats
     * @param null $now
     * @return bool|string|null
     */
    public static function getFriendlyTime($timestamp, $timeLimit = 604800, $out_format = 'Y/m/d', $formats = null, $now = null)
    {
        /*if (get_setting('time_style') == 'N')
        {
            return date($out_format, $timestamp);
        }*/

        if (!$timestamp) {
            return '--';
        }

        if ($formats == null) {
            $formats = [
                'YEAR' => '%s 年前',
//                'YEAR' =>'%s YEAR',
                'MONTH' => '%s 月前',
//                'MONTH' => '%s MONTH',
                'DAY' => '%s 天前',
//                'DAY' => '%s DAY',
                'HOUR' => '%s 小时前',
//                'HOUR' => '%s HOUR',
                'MINUTE' => '%s 分钟前',
//                'MINUTE' => '%s MINUTE',
                'SECOND' => '%s 秒前'
//                'SECOND' => '%s SECOND'
            ];
        }

        $now = $now == null ? time() : $now;
        $seconds = $now - $timestamp;

        if ($seconds == 0) {
            $seconds = 1;
        }

        if (!$timeLimit or $seconds > $timeLimit) {
//            return date($out_format, $timestamp);
        }

        $minutes = floor($seconds / 60);
        $hours = floor($minutes / 60);
        $days = floor($hours / 24);
        $months = floor($days / 30);
        $years = floor($months / 12);

        if ($years > 0) {
            $diffFormat = 'YEAR';
        } else {
            if ($months > 0) {
                $diffFormat = 'MONTH';
            } else {
                if ($days > 0) {
                    $diffFormat = 'DAY';
                } else {
                    if ($hours > 0) {
                        $diffFormat = 'HOUR';
                    } else {
                        $diffFormat = ($minutes > 0) ? 'MINUTE' : 'SECOND';
                    }
                }
            }
        }

        $dateDiff = null;


        switch ($diffFormat) {
            case 'YEAR' :
                $dateDiff = sprintf($formats[$diffFormat], $years);
                break;
            case 'MONTH' :
                $dateDiff = sprintf($formats[$diffFormat], $months);
                break;
            case 'DAY' :
                $dateDiff = sprintf($formats[$diffFormat], $days);
                break;
            case 'HOUR' :
                $dateDiff = sprintf($formats[$diffFormat], $hours);
                break;
            case 'MINUTE' :
                $dateDiff = sprintf($formats[$diffFormat], $minutes);
                break;
            case 'SECOND' :
                $dateDiff = sprintf($formats[$diffFormat], $seconds);
                break;
        }

        return $dateDiff;
    }

    /**
     * Notes:获取当天或某个日期是星期几
     * User:machangzhuo
     * DateTime: 2022/6/10 9:55
     * @param $data
     * @param string $format
     * @return string
     */
    public function getWeekName($data, $format = '星期')
    {
        $week = date("D ", $data);
        switch ($week) {
            case "Mon ":
                $current = $format . "一";
                break;
            case "Tue ":
                $current = $format . "二";
                break;
            case "Wed ":
                $current = $format . "三";
                break;
            case "Thu ":
                $current = $format . "四";
                break;
            case "Fri ":
                $current = $format . "五";
                break;
            case "Sat ":
                $current = $format . "六";
                break;
            case "Sun ":
                $current = $format . "日";
                break;
        }
        return $current;
    }

    /**
     * Notes:Discuz经典加密解密函数
     * User:machangzhuo
     * DateTime: 2022/3/15 9:29
     * @param $string  \app\api\model\明文 或 密文
     * @param string $operation DECODE表示解密,其它表示加密
     * @param string $key 密匙
     * @param int $expiry 密文有效期
     * @return false|string
     */
    public function authcode($string, $operation = 'DECODE', $key = '9527', $expiry = 0)
    {
        // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
        $ckey_length = 4;

        // 密匙
        $key = md5($key ? $key : C('AU_KEY'));

        // 密匙a会参与加解密
        $keya = md5(substr($key, 0, 16));
        // 密匙b会用来做数据完整性验证
        $keyb = md5(substr($key, 16, 16));
        // 密匙c用于变化生成的密文
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
        // 参与运算的密匙
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性
        // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $rndkey = array();
        // 产生密匙簿
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        // 核心加解密部分
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            // 从密匙簿得出密匙进行异或，再转成字符
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'DECODE') {
            // substr($result, 0, 10) == 0 验证数据有效性
            // substr($result, 0, 10) - time() > 0 验证数据有效性
            // substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
            // 验证数据有效性，请看未加密明文的格式
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
            // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }
    /**
     * Notes:随机数据
     * User:machangzhuo
     * DateTime: 2022/8/20 16:10
     * @param $arr
     * @param $int
     * @return array
     */
    public function RandArr($arr,$len=6){
        $keys=array_rand($arr,$len);
        $temp=[];
        if($keys){
            $i=0;
            foreach ($keys as $k){
                $temp[$i]=$arr[$k];
                $i++;
            }
        }

        return $temp;
    }

    /**
     * Notes:随机字符串生成
     * User:machangzhuo
     * DateTime: 2022/6/10 14:17
     * @param int $len 生成的字符串长度
     * @return string
     */
    public  function random_string($len = 6,$chars='')
    {
        $arr    = [
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        ];
        if(empty($chars)) $chars=$arr;
        $charsLen = count($chars) - 1;
        shuffle($chars);    // 将数组打乱
        $output = "";
        for ($i = 0; $i < $len; $i++) {
            $output .= $chars[mt_rand(0, $charsLen)];
        }
        return $output;
    }

    /**
     * Notes:金额格式化
     * User:machangzhuo
     * DateTime: 2022/6/10 14:11
     * @param $value [金额]
     * @param int $decimals [保留的位数]
     * @param string $dec_point [保留小数分隔符]
     * @return string
     */
    public function PriceNumberFormat($value, $decimals = 2, $dec_point = '.')
    {
        return number_format((float)$value, $decimals, $dec_point, '');
    }


    /**
     * Notes:异步调用方法
     * User:machangzhuo
     * DateTime: 2022/6/10 14:13
     * @param $url
     * @param int $port
     * @param int $time
     * @return bool
     */
    public function SyncJob($url, $port = 80, $time = 30)
    {
        // curl
        if (function_exists('curl_init')) {
            $this->CurlGet($url, 1);
            return true;

            // fsockopen
        } elseif (function_exists('fsockopen')) {
            $url_str = str_replace(array('http://', 'https://'), '', $url);
            $location = strpos($url_str, '/');
            $host = substr($url_str, 0, $location);
            $fp = fsockopen($host, $port, $errno, $errstr, $time);
            if ($fp) {
                $out = "GET " . str_replace($host, '', $url_str) . " HTTP/1.1\r\n";
                $out .= "Host: " . $host . "\r\n";
                $out .= "Content-type: application/x-www-form-urlencoded\r\n";
                $out .= "Connection: Close\r\n\r\n";
                fputs($fp, $out);
                fclose($fp);
            }
            return true;
        }
        return false;
    }


    /**
     * Notes:客户端ip地址
     * User:machangzhuo
     * DateTime: 2022/6/10 14:14
     * @param bool $long $long [是否将ip转成整数]
     * @return array|false|mixed|string
     */
    public function GetClientIP($long = false)
    {
        $onlineip = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        if ($long) {
            $onlineip = sprintf("%u", ip2long($onlineip));
        }
        return $onlineip;
    }


    /**
     * curl模拟get请求
     * @param    [string]           $url        [url地址]
     * @param    [int]              $timeout    [超时时间（默认10秒）]
     * @return   [array]                        [返回数据]
     * @version  1.0.0
     * @datetime 2018-01-03T19:21:38+0800
     * @author   Devil
     * @blog     http://gong.gg/
     */
    function CurlGet($url, $timeout = 10)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * curl模拟post
     * @param    [string]   $url        [请求地址]
     * @param    [array]    $post       [发送的post数据]
     * @param    [boolean]  $is_json    [是否使用 json 数据发送]
     * @param    [int]      $timeout    [超时时间]
     * @return   [mixed]                [请求返回的数据]
     * @version  0.0.1
     * @datetime 2016-12-03T21:58:54+0800
     * @author   Devil
     * @blog     http://gong.gg/
     */
    function CurlPost($url, $post, $is_json = false, $timeout = 30)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);

        // 是否 json
        if ($is_json) {
            $data_string = json_encode($post);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    "Content-Type: application/json; charset=utf-8",
                    "Content-Length: " . strlen($data_string)
                )
            );
        } else {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    "Content-Type: application/x-www-form-urlencoded; charset=utf-8",
                    "cache-control: no-cache"
                )
            );
        }

        // 返回结果
        $result = curl_exec($ch);
        if ($result !== false) {
            curl_close($ch);
            return $result;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return "curl出错，错误码:$error";
        }
    }



//
//    /**
//     * Notes:二维数组根据某一字段去重
//     * User:machangzhuo
//     * DateTime: 2022/3/25 15:30
//     * @param $arr
//     * @param $key
//     * @return mixed
//     */
//    public static function second_array_unique_bykey($arr, $key)
//    {
//        if(empty($arr)) return '';
//        $tmp_arr = array();
//        foreach ($arr as $k => $v) {
//            if (in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
//            {
//                unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
//            } else {
//                $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
//            }
//        }
//        //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
//        return $arr;
//
//    }

    /**
     * machangzhuo 判断字符串是否包含某一值
     * Createtime: 2021/10/9
     * @param string $str 数据
     * @param string $needle 包含的字符串
     */
    public function checkstr($str, $needle)
    {

        $tmparray = explode($needle, $str);
        if (count($tmparray) > 1) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Notes:把返回的数据集转换成Tree
     * User:machangzhuo
     * DateTime:  2022/2/24 17:09
     * @param $list要转换的数据集
     * @param string $pk 自增字段（栏目id）
     * @param string $pid parent标记字段
     * @param string $child
     * @param int $root
     * @return array
     */
    public function make_tree($list, $pk = 'id', $pid = 'parent_id', $child = '_child', $root = 0)
    {
        $tree = array();
        $packData = array();
        foreach ($list as $data) {
            $packData[$data[$pk]] = $data;
        }
        foreach ($packData as $key => $val) {
            if ($val[$pid] == $root) {//代表跟节点
                $tree[] =& $packData[$key];
            } else {
                //找到其父类
                $packData[$val[$pid]][$child][] =& $packData[$key];
            }
        }
        return $tree;
    }


    /**
     * 传递一个父级分类ID返回所有子分类
     * @param $cate
     * @param $pid
     * @return array
     */
    public function getChilds($cate, $pid)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $pid) {
                // $v['url'] = getUrl($v);
                $arr[] = $v;
                $arr = array_merge($arr, getChilds($cate, $v['id']));
            }
        }
        return $arr;
    }


    /**
     * 传递一个父级分类ID返回当前子分类
     * @param $cate
     * @param $pid
     * @return array
     */
    public function getChildsOn($cate, $pid)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['parent_id'] == $pid) {
                $v['sub'] = \app\api\model\getChilds($cate, $v['id']);
                // $v['url'] = getUrl($v);
                $arr[] = $v;
            }
        }
        return $arr;
    }

    /**
     * 查找一个分类id的顶级分类id
     * @param $id
     * @return string
     */
    public function getTopId($id)
    {
//        $cate    = \app\common\model\Cate::field('id,parent_id')->select()->toArray();
//        $cateArr = [];
//        if ($cate) {
//            foreach ($cate as $k => $v) {
//                $cateArr[$v['id']] = $v['parent_id'] ?: "0";
//            }
//        }
//        while ($cateArr[$id]) {
//            $id = $cateArr[$id];
//        }
//        return $id;
    }


    /**
     * 传递一个子分类ID返回所有的父级分类[前台栏目]getParents
     * @param $cate
     * @param $id
     * @return array
     */
    public function getParents($cate, $id)
    {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['id'] == $id) {
                $arr[] = $v;
                $arr = array_merge(getParents($cate, $v['parent_id']), $arr);
            }
        }
        return $arr;
    }


    /**
     * 获取数据的所有子孙数据的id值
     */

  public  function get_stemma($pids,Model &$model, $field='id'){
        $collection = array();

        //非空判断
        if(empty($pids)){
            return $collection;
        }

        if( is_array($pids) ){
            $pids = trim(implode(',',$pids),',');
        }
        $result     = $model->field($field)->where(array('pid'=>array('IN',(string)$pids)))->select();
        $child_ids  = array_column ((array)$result,'id');

        while( !empty($child_ids) ){
            $collection = array_merge($collection,$result);
            $result     = $model->field($field)->where( array( 'pid'=>array( 'IN', $child_ids ) ) )->select();
            $child_ids  = array_column((array)$result,'id');
        }
        return $collection;
    }

    /**
     * 二维数组按两个字段排序
     * @param $data
     * @param $key
     * @param $key2
     * @param $sort
     * @return mixed
     */
    public function array2MultiSort($data,$key,$key2,$sort='DESC'){

        $ages = array_column($data, $key);
        $names = array_column($data, $key2);
        $sort=$sort=='DESC'?SORT_DESC:SORT_ASC;
        array_multisort($ages, $sort, $names, $sort, $data);
        return $data;

    }



}